package com.hd.trans.ui.model;


import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.hd.trans.R;
import com.hd.trans.common.Constants;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent;
import com.hd.trans.network.component.LangDetectComponent;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.preference.Preferences;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;


/**
 * Author: yang
 * Date: 2020/1/6 18:36
 * Desc: 文本翻译页面数据
 */
public class HomeTextModel extends ViewModel {

    private MutableLiveData<HuDunLanguage> mLanguageFrom; // 源语言
    private MutableLiveData<HuDunLanguage> mLanguageTo; // 目标语言
    private MutableLiveData<HuDunLanguage> mDetectLang ; // 检测到的语言

//    Constants.TranslatePageState

    /**
     * 当前状态
     *
     * @see Constants.TranslatePageState
     */
    private MutableLiveData<Integer> mTranslateState;

    private MutableLiveData<TranslateRecord> mOperateRecord; // 当前操作记录

    private MutableLiveData<List<TranslateRecord>> listTranslateRecord = new MutableLiveData<>(); // 历史记录

    public MutableLiveData<HuDunLanguage> getLanguageFrom() {
        if (mLanguageFrom == null) {
            String fromLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansFromLanguage();
            setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
        }
        return mLanguageFrom;
    }

    public void setLanguageFrom(HuDunLanguage item) {
        if (mLanguageFrom == null) {
            mLanguageFrom = new MutableLiveData<>();
        }
        mLanguageFrom.setValue(item);
    }

    public MutableLiveData<HuDunLanguage> getLanguageTo() {
        if (mLanguageTo == null) {
            String toLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansToLanguage();
            setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));
        }
        return mLanguageTo;
    }

    public void setLanguageTo(HuDunLanguage item) {
        if (mLanguageTo == null) {
            mLanguageTo = new MutableLiveData<>();
        }
        mLanguageTo.setValue(item);
    }

    public void setDetectLang(HuDunLanguage detectLang) {
        if (mDetectLang == null) {
            mDetectLang = new MutableLiveData<>();
        }
        mDetectLang.setValue(detectLang);
    }

    public MutableLiveData<HuDunLanguage> getDetectLang() {
        if (mDetectLang == null) {
            mDetectLang = new MutableLiveData<>();
        }
        return mDetectLang;
    }

    public MutableLiveData<Integer> getTranslateState() {
        if (mTranslateState == null) {
            mTranslateState = new MutableLiveData<>();
        }
        return mTranslateState;
    }

    public void setTranslateState(Integer val) {
        if (mTranslateState == null) {
            mTranslateState = new MutableLiveData<>();
        }
        mTranslateState.setValue(val);
    }


    public MutableLiveData<TranslateRecord> getOperateRecord() {
        if (mOperateRecord == null) {
            mOperateRecord = new MutableLiveData<>();
        }
        return mOperateRecord;
    }

    public void setOperateRecord(TranslateRecord item) {
        if (mOperateRecord == null) {
            mOperateRecord = new MutableLiveData<>();
        }
        mOperateRecord.setValue(item);
    }

    public MutableLiveData<List<TranslateRecord>> getListTranslateRecord() {
        return listTranslateRecord;
    }

    public void setListTranslateRecord(List<TranslateRecord> listTranslateRecord) {
        this.listTranslateRecord.setValue(listTranslateRecord);
    }

    public void languageDetect(String text) {
        LangDetectComponent.INSTANCE.firstLangDetect(text,(result)->{
            if (result == null)
                return null;
            if (result.equals("br")){
                result = "en";
            }
            HuDunLanguage language = DataBaseMgr.getInstance().getLanguageByTransCode(result);
            if (language != null){
                setDetectLang(language);
            }
            return null;
        });
    }

    public void getRecordById(long recordId) {
        TranslateRecord record = DataBaseMgr.getInstance().getRecordById(recordId);
        mOperateRecord.setValue(record);
    }

    /**
     * 收藏
     */
    public void collectRecord() {
        TranslateRecord record = mOperateRecord.getValue();
        if (record != null){
            record.setIsCollected(!record.getIsCollected());
            DataBaseMgr.getInstance().updateTranslateRecord(record);
            mOperateRecord.setValue(record);
        }
    }

    /**
     * 翻译
     */
    public void translationText(
            HdTranslateComponent translateComponent,
            String origContent
    ) {
        if (mLanguageFrom.getValue() == null || mLanguageTo.getValue() == null) {
            return;
        }
        translateComponent.translationText(
                origContent,
                mLanguageFrom.getValue().getTranslateCode(),
                mLanguageTo.getValue().getTranslateCode(),
                false,
                new TranslateCallback() {
                    @Override
                    public void onTranslateFailed(int code, String msg) {
                        if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                || code == Constants.ResponseCode.ERROR_COMM){
                            ToastUtils.showError(msg);
                        }else {
                            ToastUtils.showError(R.string.fanyi_faith_tip);
                        }
                    }

                    @Override
                    public void onTranslateCompleted(
                            String data,
                            String fromLangCode,
                            String toLangCode,
                            boolean status
                    ) {
                        //创建翻译记录
                        TranslateRecord record = new TranslateRecord();
                        record.setIsVoice(false);
                        record.setIsNation(false);
                        record.setIsCollected(false);
                        record.setLanguageFrom(mLanguageFrom.getValue());
                        record.setLanguageTo(mLanguageTo.getValue());
                        record.setContentOrig(origContent);
                        record.setContentTranslate(data);
                        record.setTriggerTime(System.currentTimeMillis());

                        if(Preferences.INSTANCE.isOffline() || !Preferences.INSTANCE.isPinyinEnable()){
                            DataBaseMgr instance = DataBaseMgr.getInstance();
                            //重复数据。就删除前面的历史数据
                            //instance.isContain(record);
                            instance.addTranslateRecord(record);

                            mOperateRecord.setValue(record);

                            //刷新历史记录
                            refreshRecords();
                        }else {
                            //标音
                            getResultPinyin(
                                    origContent,
                                    mLanguageFrom.getValue(),
                                    data,
                                    mLanguageTo.getValue()
                            );
                        }
                    }
                }
        );
    }

    private void getResultPinyin(
            String origContent,
            HuDunLanguage fromLang,
            String data,
            HuDunLanguage toLang
    ) {

    }

    public void refreshRecords() {
        Observable.create((ObservableOnSubscribe<List<TranslateRecord>>) emit -> {
                    emit.onNext(DataBaseMgr.getInstance().getAllRecords(false, false));
                    emit.onComplete();
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<List<TranslateRecord>>() {
                    @Override
                    public void onNext(List<TranslateRecord> list) {
                        setListTranslateRecord(list);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}